/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "StockDayDatabase.h"

#include <QtCore/QFile>
#include <QtCore/QDir>

namespace QSThink
{

	StockDayFile* StockDayDatabase::getStockDayFile(QString symbol)
	{
 		std::map<QString,StockDayFile*>::iterator it=_files.find(symbol);
		if(it!=_files.end()){
			return it->second;
		}

		return 0;

	}

	StockDayFile* StockDayDatabase::getStockDayFile( int index )
	{
		int size=_files.size();
		if(index<0||index>=size){
			return 0;
		}
		std::map<QString,StockDayFile*>::iterator it=_files.begin();
		for (int i=0;i<index;i++)
		{
			it++;
		}
		
		return it->second;
	}

	StockDayDatabase::StockDayDatabase()
	{
		initDayDatabase();
	}

	void StockDayDatabase::initDayDatabase()
	{

		QDir dir("day");//hollova
		QFileInfoList list=dir.entryInfoList();
		int cnt=list.size();
		for(int i=0;i<cnt;++i){
			QFileInfo info=list[i];
			QString ext=info.suffix();
			if(ext=="day"){
				/*QString symbol=info.baseName().right(6);*/
				QString symbol=info.baseName().right(6);

				//sh shanghai sz shenzhen +
				StockDayFile* f=new StockDayFile(info.baseName());
				_files.insert(std::map<QString,StockDayFile*>::value_type(symbol,f));

			}
		}


	}

	int StockDayDatabase::getStockCount()
	{
		return _files.size();
	}


	StockDayFile::StockDayFile( QString symbol ) : _symbol(symbol),_valid(false)
	{
		loadFromFile(symbol);

	}

	void StockDayFile::loadFromFile( QString symbol )
	{
		QString fileName="day/"+symbol+".day";

		QFile file(fileName);
		if (!file.open(QFile::ReadOnly)){
			return ;
		}

		QByteArray bytes=file.readAll();

		int size=sizeof(StockDayFileItem);
		int cnt=bytes.length()/size;

		char* data=bytes.data();
		int index=0;

		for (int i=0;i<cnt;++i){
			int date=*(int*)(data+index);
			index+=sizeof(date);

			int open=*(int*)(data+index);
			index+=sizeof(open);

			int high=*(int*)(data+index);
			index+=sizeof(high);

			int low=*(int*)(data+index);
			index+=sizeof(low);

			int close=*(int*)(data+index);
			index+=sizeof(close);


			float amount=*(float*)(data+index);
			index+=sizeof(amount);

			int vol=*(int*)(data+index);
			index+=sizeof(vol);

			int reservation=*(int*)(data+index);
			index+=sizeof(reservation);


			StockDayFileItem* item=new StockDayFileItem;
			item->amount=amount;
			item->close=close;
			item->date=date;
			item->high=high;
			item->low=low;
			item->open=open;
			item->vol=vol;
			item->reservation=reservation;

			_items.push_back(item);
		}
		
	}

	double StockDayFile::openPriceAverage()
	{
		int cnt=_items.size();
		double p=0;
		for (int i=0;i<cnt;i++)
		{
			p+=_items[i]->open;
		}

		p/=cnt;
		return p;
	}

}
